package com.sec.security;

import com.sec.controller.IndexController;
import com.sec.dao.mysql.UserAccessLogDao;
import com.sec.domain.mysql.UserAccessLog;
import org.springframework.beans.factory.annotation.Configurable;
import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

/**
 * 资源管理拦截器
 * 1. 调用MyInvocationSecurityMetadataSource的getAttributes(Object object)这个方法获取fi对应的所有权限
 * 2. 再调用MyAccessDecisionManager的decide方法来校验用户的权限是否足够
 * Created by Administrator on 2017/10/31.
 */
@Configurable
public class MyFilterSecurityInterceptor extends AbstractSecurityInterceptor  implements Filter {

    //配置文件注入
    private FilterInvocationSecurityMetadataSource securityMetadataSource;
    @Resource
    private UserAccessLogDao userAccessLogDao;
    @Resource
    IndexController indexController;

    //登陆后，每次访问资源都通过这个拦截器拦截
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        FilterInvocation fi = new FilterInvocation(request, response, chain);
        invoke(fi);
    }

    public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {
        return this.securityMetadataSource;
    }

    public Class<? extends Object> getSecureObjectClass() {
        return FilterInvocation.class;
    }

    public void invoke(FilterInvocation fi) throws IOException, ServletException {
        //fi里面有一个被拦截的url
        //里面调用MyInvocationSecurityMetadataSource的getAttributes(Object object)这个方法获取fi对应的所有权限
        //再调用MyAccessDecisionManager的decide方法来校验用户的权限是否足够
        InterceptorStatusToken token = super.beforeInvocation(fi);
        try {
            //执行下一个拦截器
            fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
        } finally {
            super.afterInvocation(token, null);
        }

        // 记录用户访问url次数
        urlCount(fi);
    }

    /**
     * 记录用户访问url次数
     * */
    private void urlCount(FilterInvocation fi) throws ServletException, IOException {
        //UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Object user = null;
        if(SecurityContextHolder.getContext().getAuthentication()!=null){
            user = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        }
        if(user !=null && user instanceof UserDetails){
            UserDetails userDetails = (UserDetails) user;
            String username = userDetails.getUsername();
            UserAccessLog userAccessLog = new UserAccessLog();
            userAccessLog.setUsername(username);
            userAccessLog.setAccessUrl(fi.getRequestUrl());
            List<UserAccessLog> userAccessLogList = userAccessLogDao.queryByCon(userAccessLog);
            if(userAccessLogList!=null && userAccessLogList.size()>0){ // 如果有记录，访问次数+1
                userAccessLog = userAccessLogList.get(0);
                int count = userAccessLog.getUrlCount();
                userAccessLog.setUrlCount(count+1);
                userAccessLogDao.update(userAccessLog);

            }else{ //没记录添加一条新的记录
                userAccessLog.setUrlCount(1);
                userAccessLogDao.save(userAccessLog);
            }
        }/*else if(user.toString().equals("anonymousUser")){ //
            if(!fi.getRequest().getRequestURL().toString().contains("logout")){
                //if(!fi.getResponse().isCommitted()){
                    fi.getResponse().sendRedirect("/login");
                //}
            }
        }*/

    }

    public SecurityMetadataSource obtainSecurityMetadataSource() {
        return this.securityMetadataSource;
    }
    public void setSecurityMetadataSource(
            FilterInvocationSecurityMetadataSource newSource)
    {
        this.securityMetadataSource = newSource;
    }
    public void destroy() {

    }
    public void init(FilterConfig arg0) throws ServletException {

    }
}